<?php
namespace app\admin\command;

use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Lang;
use think\Loader;

class Miner extends Command
{
    protected function configure()
    {
        $this->setName('miner')
        ->addOption('type', 't', Option::VALUE_REQUIRED, 'operation type without', null)
        ->setDescription('Mine operation');
    }

    protected function execute(Input $input, Output $output)
    {
        $type = $input->getOption('type');
        if(!$type){
           $type = 'r';
        }
        switch ($type) {
            //发币
            case 'r':
                $miner_switch = Db::name('config')->where(['name'=>'miner_switch','group'=>'switch'])->value('value');
                if($miner_switch == 0){
                   $output->writeln('Miner operation closed');
                   die; 
                }
                //满足运行时间
                $all_cycle_miner = Db::name('user_miner')
                //->where('createtime','<=',$now)
                ->where('status','eq',1)
                ->select();
                $i = 0;
                foreach ($all_cycle_miner as $key => $value) {
                    //该用户是否已拉黑
                    $status = Db::name("user")->where('id', $value['user_id'])->value('status');
                    if($status!='normal'){
                        continue;
                    }
                    //限制一天多次产矿
                    $lasttime = date('Y-m-d',$value['lasttime']);
                    $today = date('Y-m-d');
                    if($lasttime ==$today){
                        continue;
                    }
                    $miner_data = Db::name('miner')->where(['id'=>$value['miner_id']])->find();
                    $output_value = $miner_data['output_value']>0?$miner_data['output_value']:0;
                    // 启动事务
                    Db::startTrans();
                    try{
                        //运行中的矿机产矿
                        //if($value['status'] ==1 && $output_value>0){
                        if($output_value>0){
                            //矿机产生收益记录
                            $user_output_log['user_id']       = $value['user_id'];
                            $user_output_log['miner_id']      = $value['miner_id'];
                            $user_output_log['miner_cat']     = $value['miner_cat'];
                            $user_output_log['output']        = $output_value;
                            $user_output_log['user_miner_id'] = $value['id'];
                            $user_output_log['createtime']    = time();
                            Db::name('user_output_log')->insert($user_output_log);
                            Db::name('user_miner')
                            ->where(['id'=>$value['id']])
                            ->update([
                                'lasttime' => time(),
                                'sum_output' => Db::raw('sum_output+' . $output_value),
                                'runed_cycle' => Db::raw('runed_cycle+1'),
                                'status'=>2
                            ]);
                            $i++;
                        }
                        // 提交事务
                        Db::commit(); 
                    } catch (\think\Exception\DbException $exception){
                        Db::rollback();
                    }
                    
                }
                $output->writeln($i);
                break;
            //体验矿机
            case 's':
                $miner_switch = Db::name('config')->where(['name'=>'miner_switch','group'=>'switch'])->value('value');
                if($miner_switch == 0){
                   $output->writeln('Miner operation closed');
                   die; 
                }
                $miner_last_time = Db::name('config')
                ->where(['group'=>'miner','name'=>'miner_last_time'])
                ->value('value');
                if($miner_last_time){
                    $lasttime = date('Y-m-d',$miner_last_time);
                    $today = date('Y-m-d');
                    if($lasttime ==$today){
                        $output->writeln('Miner already run on today');
                        die;
                    }
                }
                //排除周末
                 // $now = time();
                 // if((date('w',strtotime($now)) == 0)){
                 // return false;
                 // }
                //满足运行时间
                $output_value = Db::name('config')
                ->where(['group'=>'miner','name'=>'output_value'])
                ->value('value');
                if($output_value <= 0){
                   $output->writeln('Miner operation zero');
                   die; 
                }
                $active_price = Db::name('config')
                ->where(['group'=>'miner','name'=>'active_price'])
                ->value('value');
                $all_user = Db::name('user')
                ->where('status','normal')
                ->select();
                $i = 0;
                foreach ($all_user as $key => $value) {
                    $userinfo = Db::name('user')
                    ->where('id',$value['id'])
                    ->lock(true)
                    ->find();
                    // 启动事务
                    Db::startTrans();
                    try{
                        //运行中的矿机产矿
                        if($userinfo['mq']>=$active_price && $output_value>0){
                            //矿机产生收益记录
                            $user_output_log['user_id']       = $value['id'];
                            $user_output_log['miner_id']      = 0;
                            $user_output_log['miner_cat']     = 0;
                            $user_output_log['output']        = $output_value;
                            $user_output_log['user_miner_id'] = 0;
                            $user_output_log['createtime']    = time();
                            Db::name('user_output_log')->insert($user_output_log);
                            $i++;
                            if($active_price>0){
                                 $res = Db::name('user')
                                ->where('id',$value['id'])
                                ->setDec('mq',$active_price);
                                if($res){
                                    //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                                    $user_balance_log['user_id']    = $value['id'];
                                    $user_balance_log['amount']     = $active_price;
                                    $user_balance_log['before']     = $userinfo['mq'];
                                    $user_balance_log['after']      = $userinfo['mq']-$active_price;
                                    $user_balance_log['remark']     = '激活矿机';
                                    $user_balance_log['type']       = 0;
                                    $user_balance_log['log_type']   = 3;
                                    $user_balance_log['source']     = 8;
                                    $user_balance_log['createtime'] = time();
                                    Db::name('user_balance_log')->insert($user_balance_log);
                                }
                            }
                        }
                        // 提交事务
                        Db::commit(); 
                        
                    } catch (\think\Exception\DbException $exception){
                        Db::rollback();
                    }
                    
                }
                Db::name('config')
                ->where(['group'=>'miner','name'=>'miner_last_time'])
                ->update([
                    'value' => time()
                ]);
                $output->writeln($i);
                break;
            //激活
            case 'a':
                $miner_switch = Db::name('config')->where(['name'=>'miner_switch','group'=>'switch'])->value('value');
                if($miner_switch == 0){
                   $output->writeln('Miner active closed');
                   die; 
                }
                $all_miner = Db::name('user_miner')
                ->where(['status'=>2])
                ->select();
                $i=0;
                foreach ($all_miner as $key => $value) {
                    //限制一天多次激活
                    $active_time = date('Y-m-d',$value['active_time']);
                    $today = date('Y-m-d');
                    if($active_time == $today){
                        continue;
                    }
                    $miner_data = Db::name('miner')
                    ->where(['id'=>$value['miner_id']])
                    ->find();

                    $active_price = $miner_data['active_price'];
                    $runed_cycle = $value['runed_cycle'];
                    $userinfo = [];
                    // 启动事务
                    Db::startTrans();
                    try{
                        if($miner_data['run_cycle'] > $runed_cycle){
                            $userinfo = Db::name('user')
                            ->where('id',$value['user_id'])
                            ->lock(true)
                            ->find();
                            if($userinfo['mq']>=$active_price){//扣除矿机激活消耗MQ
                                Db::name('user_miner')
                                ->where(['id'=>$value['id']])
                                ->update([
                                    'active_time' => time(),
                                    'status' => 1
                                ]);
                                $res = Db::name('user')
                                ->where('id',$value['user_id'])
                                ->setDec('mq',$active_price);
                                $i++;
                                if($res){
                                    //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                                    $user_balance_log['user_id']    = $value['user_id'];
                                    $user_balance_log['amount']     = $active_price;
                                    $user_balance_log['before']     = $userinfo['mq'];
                                    $user_balance_log['after']      = $userinfo['mq']-$active_price;
                                    $user_balance_log['remark']     = '激活矿机';
                                    $user_balance_log['type']       = 0;
                                    $user_balance_log['log_type']   = 3;
                                    $user_balance_log['source']     = 8;
                                    $user_balance_log['createtime'] = time();
                                    Db::name('user_balance_log')->insert($user_balance_log);
                                }
                            }
                        }
                        // 提交事务
                        Db::commit(); 
                    } catch (\think\Exception\DbException $exception){
                        Db::rollback();
                    }
                }
                $output->writeln($i);
                break;
            default:
                # code...
                break;
        }
        
    }
}